<template>
  <CommonPage show-footer :show-header="false">
    <CrudTable
      ref="$table"
      v-model:query-items="queryItems"
      :extra-params="extraParams"
      :columns="columns"
      :get-data="api.getUserList"
    >
      <template #queryBar>
        <QueryBarItem label="用户姓名" :label-width="70">
          <n-input
            type="text"
            clearable
            placeholder="请输入用户姓名"
            @keydown.enter="$table?.handleSearch"
            v-model:value="queryItems.searchKey"
          />
        </QueryBarItem>
        <QueryBarItem label="用户状态" :label-width="70">
          <n-select
            clearable
            filterable
            placeholder="请选择用户状态"
            :options="getOptions('COMMON_STATUS')"
            @keydown.enter="$table?.handleSearch"
            v-model:value="queryItems.userStatus"
          />
        </QueryBarItem>
      </template>

      <template #title-right>
        <n-button
          type="primary"
          size="small"
          :disabled="!checkIsAuth('userAdd')"
          @click="handleAdd"
        >
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5" />
          新增用户
        </n-button>
      </template>
    </CrudTable>

    <!-- 新增/编辑/查看 -->
    <CrudModal
      style="width: 580px"
      :title="modalTitle"
      :loading="modalLoading"
      :show-footer="modalAction !== 'view'"
      @on-save="handleSave"
      v-model:visible="modalVisible"
    >
      <n-form
        ref="modalFormRef"
        label-placement="left"
        label-width="100"
        :model="modalForm"
        :disabled="modalAction === 'view'"
      >
        <n-form-item
          label="账号"
          path="name"
          :rule="{
            required: true,
            message: '请输入账号',
          }"
        >
          <n-input
            clearable
            placeholder="请输入账号"
            v-model:value="modalForm.account"
          />
        </n-form-item>
        <n-form-item
          label="姓名"
          path="name"
          :rule="{
            required: true,
            message: '请输入姓名',
          }"
        >
          <n-input
            clearable
            placeholder="请输入姓名"
            v-model:value="modalForm.name"
          />
        </n-form-item>
        <n-form-item
          label="角色"
          path="roleIdList"
          :rule="{
            required: true,
            message: '请选择角色',
          }"
        >
          <n-select
            clearable
            filterable
            multiple
            placeholder="请选择角色"
            label-field="name"
            value-field="id"
            :options="roles"
            v-model:value="modalForm.roleIdList"
          />
        </n-form-item>
        <n-form-item
          label="街道"
          path="streetIdList"
          :rule="{
            required: true,
            message: '请选择街道',
          }"
        >
          <n-select
            clearable
            filterable
            multiple
            placeholder="请选择街道"
            label-field="name"
            value-field="id"
            :options="streets"
            v-model:value="modalForm.streetIdList"
          />
        </n-form-item>
        <n-form-item
          label="性别"
          path="gender"
          :rule="{
            required: true,
            message: '请选择性别',
          }"
        >
          <n-radio-group name="radiogroup" v-model:value="modalForm.gender">
            <n-space>
              <n-radio
                v-for="v in getOptions('GENDER')"
                :key="v.value"
                :value="v.value"
              >
                {{ v.label }}
              </n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="备注" path="extJson">
          <n-input
            type="textarea"
            clearable
            placeholder="请输入备注"
            v-model:value="modalForm.extJson"
          />
        </n-form-item>
      </n-form>
    </CrudModal>
  </CommonPage>
</template>

<script setup>
import { h, onMounted } from 'vue'
import { NButton, NText, NSwitch } from 'naive-ui'
import { renderIcon, getOptions, checkIsAuth } from '@/utils'
import { useCRUD } from '@/composables'
import api from './api'

const $table = ref(null)
const router = useRouter()
const queryItems = ref({
  userStatus: null,
})
const extraParams = ref({})

const columns = [
  {
    title: '序号',
    key: 'tableIndex',
    width: 100,
  },
  {
    title: '用户姓名',
    key: 'name',
    width: 150,
  },
  {
    title: '用户角色',
    width: 200,
    render(row) {
      return h(
        NText,
        {},
        {
          default: () => row.roleList.map((v) => v.name).join(','),
        }
      )
    },
  },
  {
    title: '用户状态',
    width: 100,
    render(row) {
      return h(NSwitch, {
        checkedValue: 'ENABLE',
        unCheckedValue: 'DISABLED',
        value: row.userStatus,
        loading: !!row.publishing,
        onUpdateValue: async () => {
          try {
            row.publishing = true

            const params = {
              id: row.id,
            }

            const { code } =
              row.userStatus === 'ENABLE'
                ? await api.close(params)
                : await api.open(params)

            if (code === 200) {
              row.publishing = false
              row.userStatus =
                row.userStatus === 'ENABLE' ? 'DISABLED' : 'ENABLE'
              $message.success('操作成功')
            }
          } catch (err) {
            row.publishing = false
          }
        },
      })
    },
  },
  {
    title: '所属街道',
    width: 220,
    ellipsis: { tooltip: true },
    render(row) {
      return h(
        NText,
        {},
        {
          default: () => row.streetList.map((v) => v.name).join(','),
        }
      )
    },
  },
  {
    title: '创建时间',
    key: 'createTime',
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    fixed: 'right',
    render(row) {
      return [
        h(
          NButton,
          {
            type: 'primary',
            size: 'small',
            secondary: true,
            style: 'margin-right: 10px;',
            disabled: !checkIsAuth('userEdit'),
            onClick: () => {
              handleEdit({
                id: row.id,
                account: row.account,
                name: row.name,
                roleIdList: row.roleList.map((v) => v.id),
                streetIdList: row.streetList.map((v) => v.id),
                gender: row.gender,
                extJson: row.extJson,
              })
            },
          },
          {
            default: () => '编辑',
            icon: renderIcon('material-symbols:edit-outline', { size: 14 }),
          }
        ),

        h(
          NButton,
          {
            type: 'error',
            size: 'small',
            secondary: true,
            onClick: () => handleDelete([{ id: row.id }]),
          },
          {
            default: () => '删除',
            icon: renderIcon('material-symbols:delete-outline', { size: 14 }),
          }
        ),
      ]
    },
  },
]

const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleView,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '用户',
  initForm: {},
  doCreate: api.updateUser,
  doDelete: api.delUser,
  doUpdate: api.updateUser,
  refresh: () => $table.value?.handleSearch(),
})

const roles = ref([])
const streets = ref([])

onMounted(() => {
  getRoleList()
  getStreetList()
  $table.value?.handleQuery()
})

async function getRoleList() {
  const params = {
    current: 1,
    size: 100000,
  }

  const { code, data } = await api.getRoleList(params)

  if (code === 200) {
    roles.value = data.records
  }
}

async function getStreetList() {
  const { code, data } = await api.getStreetList()

  if (code === 200) {
    streets.value = data
  }
}
</script>

<style lang="scss" scoped>
:deep(.n-card) {
  border: none !important;
}

:deep(.n-card__content) {
  padding: 0 !important;
  background-color: #f5f6fb !important;
}
</style>
